/* 
 * This file part of cget - A libcurl based downloading tool.
 * http://lianwei3.googlepages.com/home2
 * Copyright (C) 2006 Wei Lian <lianwei3@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#include "header.h"
#include "curl.h"

pthread_mutex_t lock;

int main(int argc, char **argv)
{
    int i;
    const char *outfile = NULL;
    ///parse cmdline
    while ((i = getopt(argc, argv, ":o:O:")) != -1) {
	switch (i) {
	case 'O':
	case 'o':
	    outfile = optarg;
	    break;
	default:
	  EXIT:
	    printf("Usage: cget url1 url2 ... [-O output_file]\n");
	    exit(1);
	}
    }
    int opt_num = 2;
    if (optind == 1) {		///no option
	opt_num = 0;
    }
    if (optind == argc) {	///no url list
	goto EXIT;
    }
    ////get url info
    std::vector < struct BlockInfo >vec_block_info(argc - 1 - opt_num);
    for (i = optind; i < argc; i++) {
	vec_block_info.at(i - optind).length = 0;
	vec_block_info.at(i - optind).url = argv[i];
	vec_block_info.at(i - optind).vecptr = &vec_block_info;
	vec_block_info.at(i - optind).finished = FALSE;
    }
    ///verify file name consistency
    std::string str[argc - 1 - opt_num];
    for (i = 0; i < argc - 1 - opt_num; i++) {
	str[i] = vec_block_info.at(i).url;
	std::string::size_type pos = str[i].rfind("/");
	str[i] = str[i].substr(pos + 1);
    }
    for (i = 1; i < argc - 1 - opt_num; i++) {
	if (str[i] != str[0]) {
	    printf("File names are inconsistent with each other!\n");
	    exit(1);
	}
    }
    ////get output file name
    if (outfile == NULL)
	outfile = str[0].c_str();
    ///init ncurses
    initscr();
    int row, col;
    getmaxyx(stdscr, row, col);
    mvprintw(row - 1, 1, "waiting...");
    refresh();
    ///parse file header and get length
    int error;
    pthread_t tid[argc - 1 - opt_num];
    for (i = 0; i < argc - 1 - opt_num; i++) {
	vec_block_info.at(i).curl = curl_easy_init();
	vec_block_info.at(i).thread = &(tid[i]);
    }
    for (i = 0; i < argc - 1 - opt_num; i++) {
	error =
	    pthread_create(&tid[i], NULL, consistency_check,
			   &(vec_block_info.at(i)));
	assert(error == 0);
    }
    for (i = 0; i < argc - 1 - opt_num; i++) {
	error = pthread_join(tid[i], NULL);
	assert(error == 0);
    }
    ///length consistency check 
    if (vec_block_info.at(0).length == 0) {
	endwin();
	printf
	    ("The file you try to download has no file length description\n");
	exit(1);
    }
    for (i = 1; i < argc - 1 - opt_num; i++) {
	if (vec_block_info.at(i).length != vec_block_info.at(0).length) {
	    endwin();
	    printf("file lengthes are inconsistent with each other\n");
	    exit(1);
	}
    }
    ////get FILE, initial seek position, end position
    assert(outfile);
    FILE *fp = fopen(outfile, "w");
    for (i = 0; i < argc - 1 - opt_num; i++) {
	vec_block_info.at(i).num = i;
	vec_block_info.at(i).fp = fp;
	vec_block_info.at(i).seek =
	    i * vec_block_info.at(i).length / (argc - 1 - opt_num);
	vec_block_info.at(i).end =
	    (i + 1) * vec_block_info.at(i).length / (argc - 1 - opt_num) -
	    1;
    }
    assert(vec_block_info.at(argc - 1 - opt_num - 1).end ==
	   vec_block_info.at(0).length - 1);
    assert(vec_block_info.size() == uint(argc - 1 - opt_num));
    ///clear text
    mvprintw(row - 1, 1, "          ");
    refresh();
    ///create pthread
    pthread_mutex_init(&lock, NULL);
    for (i = 0; i < argc - 1 - opt_num; i++) {
	error =
	    pthread_create(&tid[i], NULL, pull_one_url,
			   &(vec_block_info.at(i)));
	assert(error == 0);
    }
    while (1) {
	sleep(1);
	int flag = TRUE;
	for (i = 0; i < argc - 1 - opt_num; i++)
	    if (vec_block_info.at(i).finished == FALSE) {
		flag = FALSE;
		break;
	    }
	if (flag == TRUE)
	    break;
    }
    for (i = 0; i < argc - 1 - opt_num; i++) {
	error = pthread_join(tid[i], NULL);
	assert(error == 0);
    }
    ////
    fclose(fp);
    ///close ncurs
    endwin();
    return 0;
}
